<template>
  <div class="rootBox">
    <vol-box
      :lazy="true"
      v-model="purchaseModel"
      title="选择采购单"
      :height="400"
      :width="1200"
      :padding="5"
      :on-model-close="cancelBtn"
    >
      <div class="box">
        <div class="topBox">
          <div class="demo-input-suffix">
            <label for="inp">单据编码：</label>
            <el-input
              id="inp"
              placeholder="单据编码"
              v-model="form.voucher"
              @keyup="voucherKeyup"
            >
            </el-input>
          </div>
          <div class="demo-input-suffix">
            <label for="select">结账类型：</label>
            <el-select
              clearable
              id="select"
              v-model="form.paymentType"
              placeholder="结账类型"
            >
              <el-option
                v-for="item in paymentTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>

          <div class="demo-input-suffix">
            <label for="select">供应商：</label>
            <el-select
              clearable
              disabled
              id="select"
              v-model="form.supplierType"
              placeholder="供应商"
            >
              <el-option
                v-for="item in supplierTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>

          <div class="demo-input-suffix">
            <label for="select">审核状态：</label>
            <el-select
              clearable
              id="select"
              v-model="form.state"
              placeholder="审核状态"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>

          <el-button class="qureyBtn" type="primary" @click="qureyBtnFn"
            >查询</el-button
          >
        </div>

        <div class="bottomBox">
          <p class="smallTitle">采购单</p>
          <el-table
            ref="table"
            :data="tableData"
            stripe
            style="width: 100%"
            :header-cell-style="{ background: `#f8f8f9`, color: `#616161` }"
            :cell-style="purchaseApplicationText"
            border
            height="465"
            @selection-change="handleSelectionChange"
            @cell-click="purchaseApplicationVoucherFn"
          >
            <el-table-column prop="Voucher_sub" label="单据编码" width="200">
            </el-table-column>
            <el-table-column prop="Goods_num" label="数量" width="200">
            </el-table-column>
            <el-table-column prop="Total_price" label="总价" width="200">
            </el-table-column>
            <el-table-column prop="Supplier" label="供应商" width="150">
              <template #default="scope">
                <!-- <span>{{
                    scope.row.Supplier
                      ? supplierTypeOptions.find(item=>item.key==scope.row.Supplier).value
                      : ""
                  }}
                </span> -->
                <span class="purchase_state purchase_stateTwo">
                  {{
                    supplierTypeOptions.find(
                      (item) => item.key == scope.row.Supplier
                    )
                      ? supplierTypeOptions.find(
                          (item) => item.key == scope.row.Supplier
                        ).value
                      : ""
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="PaymentType" label="结账类型" width="180">
              <template #default="scope">
                <span
                  class="purchase_state"
                  :class="{
                    purchase_stateOne: scope.row.PaymentType == 0,
                    purchase_stateThree: scope.row.PaymentType == 1,
                    purchase_stateTwo: scope.row.PaymentType == 2,
                    purchase_stateZero: scope.row.PaymentType == 3,
                    purchase_stateZero: scope.row.PaymentType == 4,
                  }"
                  >{{
                    scope.row.PaymentType
                      ? paymentTypeOptions[scope.row.PaymentType].label
                      : ""
                  }}</span
                >
              </template>
            </el-table-column>
            <el-table-column prop="Contract" label="合同" width="120">
              <template #default="scope">
                <el-image
                  v-if="scope.row.Contract"
                  style="width: 70px; height: 70px"
                  :src="`${http.ipAddress + scope.row.Contract}`"
                  alt=""
                  :fit="cover"
                  :preview-src-list="[`${http.ipAddress + scope.row.Contract}`]"
                  :zoom-rate="99"
                  :max-scale="7"
                  :min-scale="0.2"
                  preview-teleported="true"
                  lazy
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="AuditStatus" label="审核状态">
              <template #default="scope">
                <span
                  class="purchase_state"
                  :class="{
                    purchase_stateOne: scope.row.AuditStatus == 0,
                    purchase_stateThree: scope.row.AuditStatus == 1,
                    purchase_stateTwo: scope.row.AuditStatus == 2,
                    purchase_stateZero: scope.row.AuditStatus == 3,
                    purchase_stateZero: scope.row.AuditStatus == 4,
                  }"
                  >{{ options[scope.row.AuditStatus].label }}</span
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>

      <template #footer>
        <div>
          <el-button type="danger" size="small" @click="cancelBtn"
            >取消</el-button
          >
        </div>
      </template>
    </vol-box>
    <!-- 弹窗 -->
    <el-dialog
      title="采购单明细"
      v-model="dialogVisible"
      width="60%"
      @close="dialogCloseFn"
    >
      <!-- <el-form :inline="true" :model="stock_in_form" class="demo-form-inline">
        <el-form-item label="商品编码">
          <el-input
            v-model="stock_in_form.goods_sub"
            placeholder="商品编码"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input
            v-model="stock_in_form.goods_name"
            placeholder="商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="入库状态">
          <el-select
            clearable
            id="select"
            v-model="stock_in_form.Goods_in_state"
            placeholder="请选择"
          >
            <el-option
              v-for="item in Goods_in_stateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" class="submitBtn"
            >查询</el-button
          >
        </el-form-item>
      </el-form> -->

      <div class="topQueryBox">
        <div class="btnFather">
          <div
            class="btnBox"
            v-for="(item, index) in Goods_in_state"
            :key="index"
            @click="btnFatherFn(index)"
            :class="{ btnBoxIndex: this.btnBoxIndex == index }"
          >
            {{ item }}
          </div>
        </div>
      </div>
      <el-table
        ref="purchaseApplicationLitsTable"
        :data="tableDataList"
        stripe
        style="width: 100%"
        :header-cell-style="{ background: `#f8f8f9`, color: `#616161` }"
        border
        height="500"
        @selection-change="handleSelectionChange2"
      >
      <!-- @row-click="clickRow" -->

        <el-table-column
          type="selection"
          width="55"
          :selectable="changeSelectable"
        >
        </el-table-column>
        <el-table-column prop="Goods_sub" label="商品编码" width="200">
        </el-table-column>
        <el-table-column prop="Goods_name" label="商品名称" width="180">
        </el-table-column>
        <el-table-column prop="Goods_num" label="数量" width="80">
        </el-table-column>
        <el-table-column prop="Goods_price" label="单价" width="80">
        </el-table-column>
        <el-table-column prop="Tax_rate" label="税率">
          <template #default="scope">
            <span class="purchase_state purchase_stateTwo">
              <!-- {{ purchase_stateArr[scope.row.Tax_rate] }} -->
              {{scope.row.Tax_rate?scope.row.Tax_rate*100+"%":""}}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="Goods_size" label="规格" width="120">
        </el-table-column>
        <el-table-column prop="Goods_in_state" label="入库状态">
          <template #default="scope">
            <span
              class="purchase_state"
              :class="{
                purchase_stateOne: scope.row.Goods_in_state == 0,
                purchase_stateThree: scope.row.Goods_in_state == 1,
                purchase_stateTwo: scope.row.Goods_in_state == 2,
              }"
              >{{ Goods_in_state[scope.row.Goods_in_state] }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="Remark" label="备注"> </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange2"
          @current-change="handleCurrentChange2"
          :current-page="currentPage2"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize2"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total2"
        >
        </el-pagination>
      </div>

      <div class="footBox">
        <el-button type="primary" @click="confirmBtnFn">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VolBox from "@/components/basic/VolBox.vue";
import purchase from "@/views/purchaseinfo/purchase/q_purchase.vue";
import paginationCom from "@/components/pagination.vue";
export default {
  components: {
    "vol-box": VolBox,
    purchase,
    paginationCom,
  },
  data() {
    return {
      btnBoxIndex: 0,
      Goods_in_state: ["未入库", "已入库", "入库中", "全部"],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      currentPage2: 1,
      pageSize2: 10,
      total2: 0,
      stock_in_form: {
        goods_sub: "",
        goods_name: "",
        Goods_in_state: "0",
      },
      purchaseModel: false,
      dialogVisible: false,
      form: {
        voucher: "",
        paymentType: "",
        state: "1",
        supplierType: "",
      },
      tableData: [],
      tableDataList: [],
      voucherSub: "",
      Goods_in_stateOptions: [
        {
          value: "0",
          label: "未入库",
        },
        {
          value: "1",
          label: "已入库",
        },
        {
          value: "2",
          label: "入库中",
        },
      ],
      paymentTypeOptions: [
        {
          value: "0",
          label: "现金",
        },
        {
          value: "1",
          label: "信用卡",
        },
        {
          value: "2",
          label: "支票",
        },
        {
          value: "3",
          label: "电子支付",
        },
        {
          value: "4",
          label: "预付款",
        },
        {
          value: "5",
          label: "赊账",
        },
        {
          value: "6",
          label: "账期",
        },
        {
          value: "7",
          label: "混合支付",
        },
      ],
      options: [
        {
          value: "0",
          label: "待审核",
        },
        {
          value: "1",
          label: "审核通过",
        },
        {
          value: "2",
          label: "审核中",
        },
        {
          value: "3",
          label: "审核未通过",
        },
        {
          value: "4",
          label: "驳回",
        },
      ],
      supplierTypeOptions: [],
      selectList: [],
    };
  },

  methods: {
    clickRow(row) {
      const selected = this.selectList.some(
        (item) => item.Goods_sub === row.Goods_sub
      );
      try {
        if (!selected) {
          // 选择
          this.selectList.push(row);
          this.$refs.purchaseApplicationLitsTable.toggleRowSelection(row, true);
        } else {
          // 取消
          var finalArr = this.selectList.filter((item) => {
            return item.Goods_sub !== row.Goods_sub;
          });
          // 取消后剩余选中的
          this.selectList = finalArr;
          this.$refs.purchaseApplicationLitsTable.toggleRowSelection(
            row,
            false
          );
        }
      } catch (error) {
        console.error(error);
      }
    },
    btnFatherFn(index) {
      this.btnBoxIndex = index;
      if (index == 3) {
        this.stock_in_form.Goods_in_state = null;
      } else {
        this.stock_in_form.Goods_in_state = index;
      }
      this.onSubmit();
    },
    dialogCloseFn() {
      this.stock_in_form = {
        goods_sub: "",
        goods_name: "",
        Goods_in_state: "0",
      };
      this.btnBoxIndex = 0;
      this.tableDataList = [];
    },
    handleSelectionChange2(val) {
      this.selectList = val;
      // this.$refs.purchaseApplicationLitsTable.toggleAllSelection(this.tableDataList,true);
    },
    changeSelectable(row) {
      return row.Goods_in_state == 0;
    },
    cancelBtn() {
      this.form = {
        voucher: "",
        paymentType: "",
        state: "1",
        supplierType: "",
        supplierTypeKey: "",
      };
      this.tableData = [];
      this.purchaseModel = false;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.qureyBtnFn();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.qureyBtnFn();
    },
    handleSizeChange2(val) {
      this.pageSize2 = val;
      this.onSubmit();
    },
    handleCurrentChange2(val) {
      this.currentPage2 = val;
      this.onSubmit();
    },
    async onSubmit() {
      let url =
        "api/q_purchaseList/xcgdgetdetailpage?id=" +
        this.ID +
        "&zt=" +
        this.stock_in_form.Goods_in_state +
        "&page=" +
        this.currentPage2 +
        "&rows=" +
        this.pageSize2;
      this.http.post(url, [], "").then((res) => {
        try {
          this.total2 = res.total;
          this.tableDataList = res.rowss;
        } catch (error) {
          console.error(error);
        }
      });
    },
    async detailPurchaseOpen(Supplier) {
      await this.selectRequest();
      console.log("Supplier1", Supplier);
      try {
        if (Supplier) {
          console.log("Supplier2", Supplier);
          this.form.supplierTypeKey = Supplier;
        }
      } catch (error) {
        console.error(error);
      }
      await this.qureyBtnFn();
      this.purchaseModel = true;
    },
    voucherKeyup(v) {
      if (v.keyCode == 13) {
        this.qureyBtnFn();
      }
    },
    purchaseApplicationText(row, column) {
      if (row.column.label == "单据编码") {
        return {
          color: "#409eff",
          cursor: "pointer",
        };
      }
    },
    async purchaseApplicationVoucherFn(row, column, event) {
      if (column.label == "单据编码") {
        if (row.AuditStatus != 1) {
          this.$message.warning("该采购单未审核通过");
          return;
        }
        // if (row.Goods_in_state != 0) {
        //   this.$message.warning(
        //     `该采购单${this.Goods_in_state[row.Goods_in_state]}`
        //   );
        //   return;
        // }

        this.voucherSub = await row.Voucher_sub;
        this.ID = row.Purchase;
        this.onSubmit();
        this.dialogVisible = true;
      }
    },
    confirmBtnFn() {
      let selectionRows =
        this.$refs.purchaseApplicationLitsTable.getSelectionRows();
      selectionRows.forEach((o) => {
        o.Voucher_sub = this.voucherSub;
        o.Cost_price =  o.Goods_price;
        o.Tax_exclusive =  Math.round((o.Goods_price / (1 + o.Tax_rate)) * 100) / 100;
        o.Tax_exclusive_total_price =   Math.round((o.Goods_num * o.Tax_exclusive) * 100) / 100
      });
      this.$emit("parentCall", ($parent) => {
        let detailRowData = $parent.$refs.detail.rowData;
        let num = 0;
        detailRowData.forEach((item) => {
          selectionRows.forEach((o) => {
            if (o.Goods_sub == item.Goods_sub) num++;
          });
        });

        if (!num) {
          $parent.$refs.detail.rowData.unshift(...selectionRows);
          this.getDatileSelectFn($parent, "Goods_sub");
          this.dialogVisible = false;
          this.purchaseModel = false;
          this.stock_in_form = {
            goods_sub: "",
            goods_name: "",
            Goods_in_state: "0",
          };
          return;
        } else {
          this.$message.error("此采购单已包含该商品");
        }
      });
    },
    voucherBtn() {
      this.dialogVisible = true;
    },
    async selectRequest() {
      let url = "api/Sys_Dictionary/GetVueDictionary";

      await this.http.post(url, ["供应商客户"], "").then((res) => {
        try {
          this.supplierTypeOptions = res[0].data;
        } catch (error) {
          console.error(error);
        }
      });
    },
  async  qureyBtnFn() {
      let url = "api/q_purchase/getPageData";
      let wheresParams = [];
      if (this.form.voucher) {
        let obj = {
          name: "Voucher_sub",
          value: this.form.voucher,
          displayType: "like",
        };
        wheresParams.push(obj);
      }
      if (this.form.paymentType) {
        console.log("this.form.paymentType", this.form.paymentType);
        let obj = {
          name: "PaymentType",
          value: this.form.paymentType,
          displayType: "select",
        };
        wheresParams.push(obj);
      }
      if (this.form.state) {
        let obj = {
          name: "AuditStatus",
          value: this.form.state,
          displayType: "select",
        };
        wheresParams.push(obj);
      }
      try {
        if (this.form.supplierTypeKey) {
          console.log("this.supplierTypeOptions", this.supplierTypeOptions);
          let key = await this.supplierTypeOptions.find(
            (item) => item.key == this.form.supplierTypeKey
          );
          this.form.supplierType = key.value
          console.log("this.form.supplierType",this.form.supplierType);
          console.log("key",key);
          let obj = {
            name: "Supplier",
            value:this.form.supplierTypeKey,
            displayType: "select",
          };
          wheresParams.push(obj);
        }
      } catch (error) {
        console.error(error);
      }
      let wheres = JSON.stringify(wheresParams);
      let param = {
        order: "desc",
        page: this.currentPage,
        rows: this.pageSize,
        sort: "CreateDate",
        wheres: wheres,
      };
      this.http.post(url, param, "").then((res) => {
        try {
          this.total = res.total;
          this.tableData = res.rows;
        } catch (error) {
          console.error(error);
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //明细表库位下拉框
    async getDatileSelectFn($parent, sub) {
      let rows = $parent.$refs.detail.rowData;
      await rows.forEach((row) => {
        $parent.$refs.detail.columns.forEach((item) => {
          if (item.field == "WHSE_name") {
            let selectUrl = `api/q_warehouse_locationList/getgoodslocation?bm=${row[sub]}`;
            item.bind.data.forEach((d) => {
              d.hidden = true;
            });
            this.http.post(selectUrl, {}, "").then((reslut) => {
              item.bind.data.forEach((d) => {
                d.hidden = true;
              });
              item.bind.data.forEach((d) => {
                reslut.rows.forEach((j) => {
                  if (d.key == j.WHSE_no) {
                    d.hidden = false;
                  }
                });
              });
              row.WHSE_name = item.bind.data.filter(
                (x) => x.hidden == false
              )[0].key;
            });
          }
        });
      });
    },
    /*
      purchaseApplicationOnSelect() {
      let selectionRows = this.$refs.table.getSelectionRows();
      selectionRows.forEach((o) => {
        o.Voucher_sub = this.form.voucher;
      });
      if (selectionRows.length) {
        this.$emit("parentCall", ($parent) => {
          let detailRowData = $parent.$refs.detail.rowData;
          let num = 0;
          detailRowData.forEach((item) => {
            selectionRows.forEach((o) => {
              o.Voucher_sub = this.form.voucher;
              if (
                o.Goods_sub == item.Goods_sub &&
                o.Voucher_sub == item.Voucher_sub
              )
                num++;
            });
          });

          if (!num) {
            let newRowObj = selectionRows.map((item) => {
              return {
                Voucher_sub: item.Voucher_sub,
                Goods_sub: item.Goods_sub,
                Goods_num: item.Goods_num,
                Goods_name: item.Goods_name,
                Goods_size: item.Goods_size,
              };
            });
            $parent.$refs.detail.rowData.unshift(...newRowObj);
            return (this.purchaseApplicationModel = false);
          } else {
            this.$message.error("此采购单已包含该商品");
          }
        });
      }
    },
    */
  },
};
</script>

<style scoped lang="less">
::v-deep .el-dialog {
  padding: 10px;
}
.btnFather {
  display: flex;
  border-bottom: 1px solid #e6e6e6;
  margin-bottom: 3px;
  .btnBox {
    line-height: 40px;
    width: 70px;
    margin: 6px 30px;
    /* border-radius: 70px; */
    overflow: hidden;
    text-align: center;
    cursor: pointer;
    /* border: 1px solid #dcdfe6; */
    /* background-color: #f5f7fa; */
  }
  .btnBoxIndex {
    color: #409eff;
    border-bottom: 2px solid #409eff;
    /* background-color: #ecf5ff; */
  }
}
.purchase_state {
  border-radius: 7px;
  padding: 2px;
  font-size: 12px;
  color: rgb(239, 180, 111);
  background-color: rgba(239, 180, 111, 0.2);
  border: 1px solid rgba(239, 180, 111, 0.3);
}
.purchase_stateZero {
  color: red;
  background-color: rgba(240, 13, 48, 0.2);
  border: 1px solid rgba(240, 13, 48, 0.3);
}
.purchase_stateOne {
  color: rgb(239, 180, 111);
  background-color: rgba(239, 180, 111, 0.2);
  border: 1px solid rgba(239, 180, 111, 0.3);
}
.purchase_stateTwo {
  color: rgb(64, 158, 255);
  background-color: rgba(64, 158, 255, 0.2);
  border: 1px solid rgba(64, 158, 255, 0.3);
}
.purchase_stateThree {
  color: rgb(7, 217, 63);
  background-color: rgba(7, 217, 63, 0.2);
  border: 1px solid rgba(7, 217, 63, 0.3);
}
.el-image-viewer__wrapper {
  z-index: 999;
}
.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
::v-deep .el-dialog {
  padding: 0 10px;
}
.block {
  display: flex;
  justify-content: right;
}
.el-form {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  align-content: center;
  padding: 0 20px;
}
.el-form > div {
  margin-bottom: 20px;
  margin-top: 20px;
  margin-right: 10px;
  .submitBtn {
    width: 80px;
  }
}
.box {
  height: 600px;
  overflow: auto;
}
.topBox {
  padding: 20px 0;
  border-bottom: 1px solid #eaeaea;
}
.el-icon-search {
  display: inline-block;
}
.topBox,
.demo-input-suffix {
  display: flex;
  line-height: 31px;
}
.demo-input-suffix {
  width: 40%;
  margin-left: 10px;
}
label {
  width: 160px;
  text-align: right;
}
.el-select {
  width: 65%;
}
.qureyBtn {
  margin-left: 30px;
  padding: 0 30px;
}
.bottomBox {
  padding: 5px;
  height: 525px;
  overflow: auto;
}

.footBox {
  float: right;
  padding: 10px 20px;
}
.confirmBtn {
  padding: 0 20px;
  pointer-events: none;
}
.smallTitle {
  color: #5d5c5c;
  font-weight: 600;
}
</style>